// 订单下方可操作的按钮列表
var order_config = {
	1: {
		tips: '待付款',
		item_class: 'isfail',
		detail_title: '等待买家付款',
		fun_btn: [
			{ btn_title: '取消订单', btn_type: 'cancel_reason', btn_status: 0 },
			{ btn_title: '去支付', btn_type: 'go_pay', btn_status: 1 },
		],
	},
	2: {
		tips: '已付款',
		item_class: 'isok',
		detail_title: '等待商家发货',
		detail_desc: '您的订单正在紧急处理中',
		fun_btn: [{ btn_title: '申请退款', btn_type: 'refund_reason', btn_status: 0 }],
	},
	3: {
		tips: '待收货',
		item_class: 'isok',
		detail_title: '商家已发货',
		detail_desc: '您的订单正在运输中',
		fun_btn: [
			// { btn_title: '申请退款', btn_type: 'refund_reason', btn_status: 0 },
			{ btn_title: '查看物流', btn_type: 'view_logistics', btn_status: 0 },
			{ btn_title: '确认收货', btn_type: 'confirm_receipt', btn_status: 1 },
		],
	},
	4: {
		tips: '已收货',
		item_class: 'isok',
		fun_btn: [],
	},
	5: {
		tips: '已取消',
		item_class: 'iscancel',
		detail_title: '交易已关闭',
		detail_desc: '超时未付款，已关闭',
		fun_btn: [{ btn_title: '删除订单', btn_type: 'delete', btn_status: 0 }],
	},
	6: {
		tips: '退款中',
		item_class: 'iscancel',
		fun_btn: [],
	},
	7: {
		tips: '已退款',
		item_class: 'isok',
		fun_btn: [],
	},
	8: {
		tips: '拒绝退款',
		item_class: 'isfail',
		fun_btn: [],
	},
	9: {
		tips: '已完成',
		item_class: 'isok',
		detail_title: '交易已完成',
		detail_desc: '交易已完成',
		fun_btn: [
			{ btn_title: '删除订单', btn_type: 'delete', btn_status: 0 },
			{ btn_title: '售后', btn_type: 'after_sales', btn_status: 0 },
		],
	},
	10: {
		tips: '已评价',
		item_class: 'isok',
		fun_btn: [
			{ btn_title: '删除订单', btn_type: 'delete', btn_status: 0 },
			{ btn_title: '售后', btn_type: 'after_sales', btn_status: 0 },
		],
	},
};

// 取消 删除 确认收货接口对应的状态值
var order_change_status_config = {
	cancel_reason: 1,
	delete: 2,
	confirm_receipt: 3,
};
// 取消 筛选弹窗的标题
var popup_title_config = {
	cancel_reason: '选择取消订单原因（必须）',
	refund_reason: '选择订单退款原因（必须）',
	order_filter: '订单筛选',
	coupon: '优惠券',
};

// 支付URL配置
var order_pay_config = {
	1: {
		url: '/order/wxpay',
		provider: 'wxpay',
	},
	4: {
		url: '/order/alipay',
		provider: 'alipay',
	},
};

// 支付URL配置
var logistics_status_config = {
	WAIT_ACCEPT: {
		title: '待揽收',
	},
	ACCEPT: {
		title: '已揽收',
	},
	TRANSPORT: {
		title: '运输中',
	},
	DELIVERING: {
		title: '派件中',
	},
	AGENT_SIGN: {
		title: '已代签收',
	},
	SIGN: {
		title: '已签收',
	},
	FAILED: {
		title: '包裹异常',
	},
};

module.exports = {
	logistics_list_init(data) {
		let _this = this;
		data.logisticsTraceDetails = _this.com_sort_list(data.logisticsTraceDetails, 'time', 'desc');
		data.logisticsTraceDetails = _this.com_arr_classify({
			_list: data.logisticsTraceDetails,
			classify_key: 'logisticsStatus',
			classify_name: 'logisticsStatus',
			classify_list_name: 'sub_list',
			o_fun: item => {
				_this.$set(item, 'logisticsStatus_title', logistics_status_config[item.logisticsStatus]['title']);
				return item;
			},
		});
		return data;
	},

	order_back_config() {
		return order_config;
	},
	refresh_add_fun(type) {
		let _this = this;
		switch (type) {
			case 'refresh':
				//刷新
				_this.loadNewsList('refresh');
				break;
			case 'pullrefresh':
				//下拉刷新
				_this.loadNewsList('pullrefresh');
				break;
			case 'add':
				//上滑加载
				_this.loadNewsList('add');
				break;
		}
	},
	//获取订单列表
	loadTabbars() {
		let _this = this;
		_this.tabBars = _this.tabBars.map(item => {
			item['loadMoreStatus'] = 0;
			item['refreshing'] = false;
			item['page'] = 1;
			item['limit'] = 20;
			item['scrollTop'] = 0;
			return item;
		});

		_this.com_loading_fun({ mode: 0 });
	},

	//列表
	loadNewsList(types) {
		let _this = this;
		let tabItem = this.tabBars[this.tabCurrentIndex];
		if (tabItem.loadMoreStatus == 1) return;
		//types add 加载更多 refresh下拉刷新

		if (types == 'add') {
			if (tabItem.loadMoreStatus == 2) {
				return;
			}
			tabItem.loadMoreStatus = 1;
		}
		// #ifdef APP-PLUS
		if (types == 'refresh') {
			tabItem.refreshing = true;
		}
		// #endif

		if (types == 'refresh') {
			tabItem.loadMoreStatus = 1;
			tabItem.page = 1;
		}

		if (types == 'pullrefresh') {
			tabItem.page = 1;
		}

		_this.$forceUpdate();
		_this.getorder(types);
	},

	order_init_item(item) {
		let _this = this;

		let _nubmer = parseInt(item.order_status);
		let item_config = _this.deepclone(order_config[_nubmer]);
		let _skulist = item.sku_list.length;

		if (_nubmer == 5 || _nubmer == 9) {
			// 已取消 已完成
			if (_skulist > 1) {
				// 加入购物车
				item_config.fun_btn.push({ btn_title: '加入购物车', btn_type: 'add_to_cart', btn_status: 1 });
			} else {
				// 再来一单
				item_config.fun_btn.push({ btn_title: '再来一单', btn_type: 'another_order', btn_status: 1 });
			}
		}

		if (item_config.fun_btn.length > 0) {
			item_config.fun_btn.forEach(vv => {
				if (vv.btn_status == 0) {
					vv['btn_config'] = { backgroundColor: '#ffffff', border: '2rpx solid #EAEDF2' };
					vv['txt_config'] = { color: '#999999', fontSize: '28rpx' };
				} else if (vv.btn_status == 1) {
					vv['btn_config'] = { backgroundColor: 'transparent', border: '2rpx solid #1FD1C2' };
					vv['txt_config'] = { color: '#1FD1C2', fontSize: '28rpx' };
				}
			});
		}
		Object.assign(item, item_config);
		return item;
	},
	async order_btn_click(block, btn) {
		let _this = this;
		let _f = false;
		let { id, order_num, sku_list, pay_way } = block;
		let { btn_type } = btn;
		let _reqdata = { order_num };
		_this.order_btn_click_data = {};

		try {
			_reqdata['order_status'] = order_change_status_config[btn_type] || false;
		} catch (error) {
			console.log(error);
		} finally {
			_this.order_btn_click_data = _reqdata;
		}
		// console.log(_this.order_btn_click_data);
		console.log(order_num, btn_type, pay_way, sku_list);
		switch (btn_type) {
			case 'cancel_reason':
				// 取消订单
				_f = await _this.com_modal({
					title: '确认取消订单？',
					content: '取消后无法恢复，优惠券可退回，有效期内使用',
					cancelText: '我再想想',
				});
				if (_f) {
					_this.order_openpopup('cancel_reason');
				}
				break;
			case 'go_pay':
				//去支付
				// 直接调取支付
				_this.order_btn_pagecallback(btn_type, {
					order_num,
					pay_way,
				});
				break;
			case 'refund_reason':
				// 申请退款
				_this.customer_wechat();
				// _this.goweburl_f(`/pagesD/shop/order_after_sale?id=${id}&order_num=${order_num}&type=${btn_type}`);
				break;
			case 'view_logistics':
				// 查看物流
				_this.goweburl_f(`/pagesD/shop/user_order_logistics?express_no=${block.express_no}&order_num=${order_num}`);
				break;
			case 'confirm_receipt':
				// 确认收货
				_f = await _this.com_modal({
					title: '确认收货？',
					content: '为了保证你的售后权益，请收到商品确认无误后再确认收货',
					cancelText: '我再想想',
				});
				if (_f) {
					_this.order_change_status(btn_type, _this.order_btn_click_data);
				}
				break;
			case 'delete':
				// 删除订单
				_f = await _this.com_modal({
					title: '确认删除订单？',
					content: '删除之后订单列表无法查看',
					cancelText: '我再想想',
				});
				if (_f) {
					_this.order_change_status(btn_type, _this.order_btn_click_data);
				}

				break;
			case 'after_sales':
				//售后
				// _this.goweburl_f(`/pagesD/shop/order_after_sale?id=${id}&order_num=${order_num}&type=${btn_type}`);
				_this.customer_wechat();
				break;
			case 'another_order':
				//再来一单
				// 跳转详情打开立即购买选好对应的skuid
				let { goods_id, rule_id: skuid, goods_number: number } = sku_list[0];
				console.log(id, skuid, number);
				_this.goweburl_f(`/pagesD/shop/good_details?id=${goods_id}&skuid=${skuid}&number=${number}&btn_type=${btn_type}`);
				break;
			case 'add_to_cart':
				//加入购物车
				console.log(order_num, btn_type, sku_list);
				let _suc = 0;
				let check_cache = uni.getStorageSync('all_spec_check_cache') || {};
				for (let index = 0; index < sku_list.length; index++) {
					let { goods_id, rule_id: spec_id, goods_number: spec_number } = sku_list[index];
					await _this.com_getdata({
						url: '/cart/add',
						id_name: 'user_id',
						data: {
							goods_id,
							spec_id,
							spec_number,
						},
						data_fun: function (res) {
							if (res.state == 1) {
								_suc++;
								check_cache[spec_id] = true;
							} else {
							}
						},
					});
				}
				uni.setStorageSync('all_spec_check_cache', check_cache);
				if (_suc > 0) {
					_this.goweburl_f(`/pagesD/shop/shop_car`);
				} else {
					_this.com_msg('加入购物车失败，该商品可能已下架~');
				}

				break;
		}
	},

	order_openpopup(v) {
		let _this = this;
		_this.popup_type = v;
		_this.popup_config['title'] = popup_title_config[v];
		_this.$nextTick(() => {
			_this.pagepopup = true;
		});
	},

	order_hidepopup() {
		let _this = this;
		try {
			if (_this.popup_type == 'order_filter') {
			} else {
				_this.popup_checked = '';
				_this.popup_checked_item = {};
			}
			_this.order_btn_click_data = {};
			_this.pagepopup = false;
		} catch (error) {
			console.log(error);
		}
	},

	popup_check_key(v) {
		let _this = this;
		let { key } = v;
		_this.popup_checked_item = v;
		_this.popup_checked = key;
	},
	popup_check_callback(type) {
		let _this = this;
		if (type == 'cancel_reason') {
			if (!_this.objJudge(_this.popup_checked)) {
				_this.com_msg('请选择取消订单原因~');
				return;
			}
			_this.$set(_this.order_btn_click_data, 'cancel_remark', _this.popup_checked_item['value']);
			_this.order_change_status(type, _this.order_btn_click_data);
		}

		if (type == 'refund_reason') {
			if (!_this.objJudge(_this.popup_checked)) {
				_this.com_msg('请选择订单退款原因~');
				return;
			}
			_this.$set(_this.page_form, 'refund_name', _this.popup_checked_item['value']);
			_this.after_sale_callback();
		}

		if (type == 'order_filter') {
			_this.page_form['order_time'] = _this.popup_checked;
			_this.$nextTick(() => {
				_this.order_hidepopup();
				_this.refresh_add_fun('refresh');
			});
		}
		if (type == 'screen_reset') {
			_this.page_form['order_time'] = '';
			_this.popup_checked = '';
			_this.popup_checked_item = {};
			_this.$nextTick(() => {
				_this.order_hidepopup();
				_this.refresh_add_fun('refresh');
			});
		}
	},

	async order_change_status(type, config) {
		let _this = this;
		let { state = 0, data = {} } = await _this.com_getdata({
			url: '/order/status',
			id_name: 'user_id',
			data: config,
			method: 'POST',
		});
		if (state == 1) {
			if (_this.pagepopup) {
				_this.order_hidepopup();
			}
			_this.order_btn_pagecallback(type, {});
		}
	},

	// 调起支付
	order_pull_pay(order_num, pay_way, suc_callback = false, fail_callback = false) {
		let _this = this;
		let { url, provider } = _this.order_back_config(pay_way);
		_this.com_getdata({
			url,
			data: {
				order_num,
			},
			// show_log: true,
			// show_data: true,
			data_fun: function (res) {
				_this.com_loading({
					status: 0,
				});
				_this.change_var.isPay = true;
				let orderInfo = res.data;
				let orderid = res.orderid;
				uni.requestPayment({
					provider,
					orderInfo,
					success: function (suc) {
						console.log(suc);
						// let rawdata = JSON.parse(suc.rawdata);
						// let result = JSON.parse(rawdata.result);
						// let no = result.alipay_trade_app_pay_response.out_trade_no;
						// console.log(rawdata, result, no);
						_this.change_var.isPay = false;
						_this.pay_callback(order_num, suc_callback);
					},
					fail(err) {
						console.log(JSON.stringify(err));
						_this.change_var.isPay = false;
						if (fail_callback) {
							fail_callback();
						} else {
							if (typeof _this.USER_ORDER_PAGE == 'undefined') {
								_this.goweburl_f('/pagesD/shop/user_order?order_status=1', 2);
							}
						}
					},
				});
			},
			fail_fun: function (res) {
				_this.change_var.isPay = false;
				_this.com_loading_fun({
					mode: 3,
					title: '支付失败',
				});
			},
		});
	},
	order_back_config(pay_way, data = false) {
		let _this = this;
		let _config = {
			1: {
				url: '/order/wxpay',
				provider: 'wxpay',
			},
			4: {
				url: '/order/alipay',
				provider: 'alipay',
			},
		};

		return _config[pay_way];
	},
	check_order_suc(order_num, numbers = 1) {
		let _this = this;
		let _max_req = 3;
		return new Promise((resolve, reject) => {
			_this.com_getdata({
				url: '/order/notify',
				id_name: '',
				data: {
					order_num,
				},
				// show_log: true,
				// show_data: true,
				data_fun: async function (res) {
					let _state = res.state;

					if (_state == 1) {
						resolve(1);
					} else if (_state == -3) {
						//  需要再请求
						if (numbers < _max_req) {
							numbers++;
							let _f = _state;
							setTimeout(async function () {
								_f = await _this.check_order_suc(order_num, numbers);
								resolve(_f);
							}, 2000);
						} else {
							resolve(_state);
						}
					} else {
						resolve(_state);
					}
				},
				fail_fun: function (res) {
					resolve(-2);
				},
			});
		});
	},
	async pay_callback(orderid, suc_callback) {
		let _this = this;
		let _no_state = 0;
		// _this.com_loading({
		// 	status: 1,
		// 	title: '处理中...',
		// });
		try {
			_no_state = await _this.check_order_suc(orderid);
		} catch (error) {
			_no_state = -2;
		}
		if (_no_state == 1) {
			// 是正确的订单
			suc_callback && suc_callback();
		} else if (_no_state == -2) {
			// 检查订单错误
			_this.com_loading_fun({
				mode: 3,
				title: '订单不存在',
			});
		} else if (_no_state == -999) {
			_this.com_loading_fun({
				mode: 3,
				title: '未知错误',
			});
		} else {
			_this.com_loading_fun({
				mode: 3,
				title: '支付失败',
			});
		}
	},
	order_config_init() {
		let _this = this;
		_this.com_getdata({
			url: '/base/config_order',
			data: {},
			method: 'GET',
			data_handle_on: false,
			data_fun: function (res) {
				if (res.state == 1) {
					_this.backstage_config_init = res.data;
				}
			},
		});
	},
};
